package com.tledu.springboot04.core;

import com.tledu.springboot04.core.exception.CustomException;
import com.tledu.springboot04.core.model.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Object handleCustomException(CustomException e, HttpServletRequest req) {
        // ajax请求
        if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
            return new AjaxResult<>(e.getMessage(), e.getCode());
        } else {
            // 页面跳转
            ModelAndView modelAndView = new ModelAndView("error");
            modelAndView.getModel().put("message", e.getMessage());
            modelAndView.getModel().put("code", e.getCode());
            return modelAndView;
        }
    }
}
